package com.cy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cy.entity.DiscussPost;
import com.cy.mapper.DiscussPostMapper;
import com.cy.service.DiscussPostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cy.util.SensitiveFilter;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cy
 * @since 2021-11-08
 */
@Service
public class DiscussPostServiceImpl extends ServiceImpl<DiscussPostMapper, DiscussPost> implements DiscussPostService {

    private static final Logger logger = LoggerFactory.getLogger(DiscussPostServiceImpl.class);

    @Autowired
    private DiscussPostService discussPostService;

    @Resource
    private SensitiveFilter sensitiveFilter;

    @Value("${caffeine.posts.max-size}")
    private int maxSize;

    @Value("${caffeine.posts.expire-seconds}")
    private int expireSeconds;

    // Caffeine核心接口: Cache, LoadingCache, AsyncLoadingCache

    // 帖子列表缓存
    private LoadingCache<String, List<DiscussPost>> postListCache;

    // 帖子总数缓存
    private LoadingCache<Integer, Integer> postRowsCache;


    @PostConstruct
    public void init() {
        // 初始化帖子列表缓存    如果缓存中无数据  caffeine会自动触发load方法
        postListCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<String, List<DiscussPost>>() {
                    @Nullable
                    @Override
                    public List<DiscussPost> load(@NonNull String key) throws Exception {
                        if (key == null || key.length() == 0) {
                            throw new IllegalArgumentException("参数错误!");
                        }

                        String[] params = key.split(":");
                        if (params == null || params.length != 2) {
                            throw new IllegalArgumentException("参数错误!");
                        }

                        int offset = Integer.valueOf(params[0]);
                        int limit = Integer.valueOf(params[1]);

                        // 二级缓存: Redis -> mysql  自己添加redis二级缓存

                        logger.debug("load post list from DB.");
                        System.out.println("load post list from DB.");
                        return find(offset, limit, 1).getRecords();
                    }
                });
    }


    @Override
    public Page<DiscussPost> findByPage(Integer current, Integer size, Integer orderMode) {
        if(current == null ){
            current = 1;
        }
        if(size == null){
            size = 10;
        }

        if (orderMode == 1) {
            return new Page<DiscussPost>().setRecords(postListCache.get(current + ":" + size));
        }

        logger.debug("load post list from DB.");


        Page<DiscussPost> page = new Page<>(current,size);
        Page<DiscussPost> discussPostPage = null;
        if(orderMode.equals(0)){
            QueryWrapper<DiscussPost> wrapper = new QueryWrapper<>();
            wrapper.orderByDesc("type")
                    .orderByDesc("create_time");
            discussPostPage = discussPostService.page(page, wrapper);
        }else {
            QueryWrapper<DiscussPost> wrapper = new QueryWrapper<>();
            wrapper.orderByDesc("type")
                    .orderByDesc("score")
                    .orderByDesc("create_time");
            discussPostPage = discussPostService.page(page, wrapper);
        }
        return discussPostPage;
    }


    @Override
    public int addDiscussPost(DiscussPost discussPost) {
        if(discussPost == null){
            throw new IllegalArgumentException("参数不能为空！");
        }

        // 转移html标记
        discussPost.setTitle(HtmlUtils.htmlEscape(discussPost.getTitle()));
        discussPost.setContent(HtmlUtils.htmlEscape(discussPost.getContent()));

        // 过滤敏感词
        discussPost.setTitle(sensitiveFilter.filter(discussPost.getTitle()));
        discussPost.setContent(sensitiveFilter.filter(discussPost.getContent()));
        return this.baseMapper.insert(discussPost);
    }

    @Override
    public int updateType(int id, int type) {
        DiscussPost discussPost = this.baseMapper.selectById(id);
        discussPost.setType(type);
        return this.baseMapper.updateById(discussPost);
    }

    @Override
    public int updateStatus(int id, int status) {
        DiscussPost discussPost = this.baseMapper.selectById(id);
        discussPost.setStatus(status);
        return this.baseMapper.updateById(discussPost);
    }


    private Page<DiscussPost> find(Integer current, Integer size, Integer orderMode){

        if(current == null ){
            current = 1;
        }
        if(size == null){
            size = 10;
        }
        Page<DiscussPost> page = new Page<>(current,size);
        Page<DiscussPost> discussPostPage = null;
        if(orderMode.equals(0)){
            QueryWrapper<DiscussPost> wrapper = new QueryWrapper<>();
            wrapper.orderByDesc("type")
                    .orderByDesc("create_time");
            discussPostPage = discussPostService.page(page, wrapper);
        }else {
            QueryWrapper<DiscussPost> wrapper = new QueryWrapper<>();
            wrapper.orderByDesc("type")
                    .orderByDesc("score")
                    .orderByDesc("create_time");
            discussPostPage = discussPostService.page(page, wrapper);
        }
        return discussPostPage;
    }


}
